package littlecyberwar.ui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.*;

import littlecyberwar.model.TrayModel;
import littlecyberwar.model.UnitTrayView;
import littlecyberwar.tool.*;
import littlecyberwar.util.*;

public class Tray extends JFrame {
  TrayModel model;
  JComboBox trayNameCombo;
  JList list;
  DefaultListModel listMod;
  Vector currSubTray;
  UnitTrayView  currTv;
  Tray thisTray;
  Integer id;
  static HashMap lookup = new HashMap();
  static HashMap lookupFromName = new HashMap();
  static Dimension size;
  
  static {
  	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();	
	int h = (int)(screenSize.height * .7);
	int w = 100;
	size = new Dimension(w,h);
  }

  class ComboBoxRenderer extends JLabel implements ListCellRenderer {
      public ComboBoxRenderer() {
          setOpaque(true);
          setHorizontalAlignment(LEFT);
          setVerticalAlignment(CENTER);
          setVerticalTextPosition(SwingConstants.BOTTOM);
          setHorizontalTextPosition(SwingConstants.CENTER);
      }
      public Component getListCellRendererComponent(
          JList list,
          Object value,
          int index,
          boolean isSelected,
          boolean cellHasFocus)
      {
          if (isSelected) {
              setBackground(list.getSelectionBackground());
              setForeground(list.getSelectionForeground());
          } else {
              setBackground(list.getBackground());
              setForeground(list.getForeground());
          }
          UnitTrayView uv= (UnitTrayView)value;
          ImageIcon icon = uv.getUnitIcon();
          if ( icon == null ){
          	Debug.out("Why is the UnitIcon here == null?");
          }
          setText(uv.getUnitName());
          setIcon(icon);
          return this;
      }
  }
  class ListSelectionHandler implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting() == false) {
	      String name = thisTray.getName();
	      int index = list.getSelectedIndex();
	      if ( index > -1 ) {
	      	// Debug.out("Unit index=" + index + " was selected from tray: " + name);
	        currTv = (UnitTrayView)currSubTray.elementAt(index);
	        Element el = currTv.getElement();
	        // stick the selected el in the diction ary
	        Util.lookup.put(Util._EL_SELECTED_FROM_TRAY, el);
	        Util.lookup.put(Util._CURR_SELECTED_TRAY, thisTray);
	        MouseHandler mh = (MouseHandler)Util.lookup.get(Util._CURR_MOUSE_HANDLER);
	        mh.setElement( el );
	      }
		}
    }
  }

  public Tray(String name, Integer idIn) {
    super(name);
    id = idIn;
    Container cont = this.getContentPane();
    cont.setLayout(new BoxLayout(cont, BoxLayout.Y_AXIS));

    trayNameCombo = new JComboBox();
    list = new JList();
    list.setCellRenderer(new ComboBoxRenderer() );
    list.setBorder(BorderFactory.createLoweredBevelBorder());
    cont.add(trayNameCombo);
    cont.add(Box.createRigidArea(new Dimension(0,3)));
    JScrollPane scrollMap = new JScrollPane(list);
    cont.add(scrollMap);
    thisTray = this;
    lookup.put(idIn, this);
	lookupFromName.put(name, this);
    // listMod = list.getModel();
    //pack();
  }

  public Dimension getPreferredSize() {
    return ( size );
  }

  public Dimension getMinimumSize() {
    return ( size );
  }

  public void setModel ( TrayModel m ) {
    model = m;
    // now setup the combobox and list from the model
    Set trayNameSet = model.getAllTrayNames();
    Object[] trayNameArray = trayNameSet.toArray();
    int arraySize = trayNameArray.length;
    for ( int i=0; i< arraySize; i++ ) {
      String currName = (String)trayNameArray[i];
      trayNameCombo.addItem(currName);
    }
    if (arraySize > 0) {
      String selectedTrayName = (String)trayNameArray[0];
      trayNameCombo.setSelectedItem(selectedTrayName);
      currSubTray = model.getTrayByName(selectedTrayName);
      list.setListData(currSubTray);
    }
    // size = list.getPreferredSize();

    // setup action handler to listen to which subtray is selected
    trayNameCombo.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
          JComboBox cb = (JComboBox)e.getSource();
          String selectedTrayName = (String)cb.getSelectedItem();
          currSubTray = model.getTrayByName(selectedTrayName);
          list.setListData(currSubTray);
        }
     });

    // setup a list action listen to listen to which unit within a tray
    // is selected
    //
    //DefaultListSelectionModel selMod = list.getSelectionModel();
    list.addListSelectionListener(new ListSelectionHandler());
    this.pack();
  }

  /**
   * The current selected view is removed and the SubTray is updated
   */
  public void removeSelectElement() {
    //System.out.println("removeSelectElement() fired");
    currSubTray.removeElement(currTv);
    Util.lookup.put(Util._EL_SELECTED_FROM_TRAY, null);
    list.setListData(currSubTray);
    currTv = null;
    list.repaint();
  }
  
  public void removeSelectElement( Vector subTray, UnitTrayView  utv ) {
	//System.out.println("removeSelectElement() fired");
	subTray.removeElement(utv);
	if ( currTv == utv ) {
		// someone just removed the currentTv
		currTv = null;
		Element el = (Element)Util.lookup.get(Util._EL_SELECTED_FROM_TRAY);
		if ( el.equals(utv.getElement())){
			Util.lookup.put(Util._EL_SELECTED_FROM_TRAY, null);
		}
	}
	list.setListData(subTray);
	list.repaint();
  }
  
  public void addSelectElement( Vector subTray, UnitTrayView  utv ){
	subTray.add(utv);
	list.setListData(subTray);
	if (currSubTray == subTray) {
		list.repaint();
	}
	return;
  }
  
  // assuming that the unitId is in the tray
  public Vector getSubTrayFromUnitId ( Integer id ) {
	// first search through all the trays 
	Set trayNameSet = model.getAllTrayNames();
	Object[] trayNameArray = trayNameSet.toArray();
	int arraySize = trayNameArray.length;
	UnitTrayView utv = null;
	Vector t = null;
	for ( int i=0; i< arraySize; i++ ) {
	  String currName = (String)trayNameArray[i];
	  // now we have a name of the tray. now we get the tray
	  t = model.getTrayByName(currName);
	  // now go through all the units
	  for (int j=0; j < t.size(); j++) {
		utv = (UnitTrayView)t.elementAt(j);
		Element el = utv.getElement();
		if (id.equals(el.getElementId())) {
			// we found a matching element Id
			return (t); 
		}
	  }
	}
	return ( t ); 	
  }
  
  public Vector getSubTrayFromName( String subTrayNameIn ){
  		return ( model.getTrayByName(subTrayNameIn));
  }
  
  /**
   * This Routine will search through the entire tray, and then try to return the UnitTrayView 
   * No data structure is changed in this case
   * @param id The element Id in question
   * @return return the matching UnitTrayView
   */
  public UnitTrayView getUnitTrayViewFromElementId( Integer id, Vector t ) {
	UnitTrayView utv = null;
	for (int j=0; j < t.size(); j++) {
		utv = (UnitTrayView)t.elementAt(j);
		Element el = utv.getElement();
	  	if (id.equals(el.getElementId())) {
	  		// we found a matching element Id
	  		return (utv); 
	  	}
	}
	return ( utv );
  }
  
  public Integer getId() {
  	return ( id );
  }
  
  public static void put( Integer trayIdIn, Tray t) {
  	lookup.put(trayIdIn, t);
  }
  
  public static Tray get( Integer trayIdIn ) {
  	return ( (Tray)lookup.get(trayIdIn));
  }
  
  public static Tray getFromName( String name ){
  	return ( (Tray)lookupFromName.get(name));
  }
  
  public void repaintList() {
	list.repaint();
  }
}